package com.blog.security.filter;

import com.blog.common.Constant;
import com.blog.security.config.JwtProperties;
import com.blog.security.util.JwtSecurityUtil;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @ClassName JwtTokenAuthenticationFilter
 * @Destription jwt token 过滤器
 * @Author 天堂小野花
 * @Date 2025/8/10  17:55
 * @Version 1.0
 */
public class JwtTokenAuthenticationFilter implements WebFilter {
    private final JwtProperties jwtProperties;

    public JwtTokenAuthenticationFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        String token = resolveToken(serverWebExchange.getRequest());
        if(StringUtils.hasLength(token)){
            //  验证token有效性
            Authentication authentication = JwtSecurityUtil.getAuthentication(token, jwtProperties.getSecretKey());
            if(authentication !=null){
                return webFilterChain.filter(serverWebExchange)
                        .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
            }
        }
        return webFilterChain.filter(serverWebExchange);

    }
    /**
     * @Author 天堂小野花
     * @Description 从请求头获取token
     * @Date 18:11 2025/8/10
     * @Param [request]
     * @return java.lang.String
     **/
    private String resolveToken(ServerHttpRequest request){
        String token = request.getHeaders().getFirst(Constant.TOKEN);
        if(StringUtils.hasLength(token)){
            return token;
        }
        return null;
    }
}
